package main

import (
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"errors"
	"time"
)

type bidBlock struct {
	//时间戳
	timestamp int64
	//当前区块的哈希值
	hash string
	//上一区块的哈希值
	prevHash string
	//序列号，用于查询
	BlockID int
	//
	EventID int64
	//地址
	nodeMAC string
	nodeIP string
	//公钥
	nodePe string
}

//新建区块
func NewBidBlock(eventId int64, nodeMAC, nodeIP, nodePe string) *bidBlock {
	b := new(bidBlock)
	b.nodeMAC = nodeMAC
	b.nodeIP = nodeIP
	b.nodePe = nodePe
	b.EventID = eventId
	b.timestamp = time.Now().UnixNano()
	return b
}

//链接上下区块
func (b *bidBlock)LinkBid(db *sql.DB){
	//log.Println(b.EventID)
	if preHash := NowBidHash(db, b.EventID); preHash != ""{
		//log.Println(preHash)
		b.prevHash = preHash
	}
}

//封装区块
func (b *bidBlock)Seal() {
	b.timestamp = time.Now().UnixNano()
	b.hash = b.HashBlock()
}

//获取区块的hash值
func (b *bidBlock)HashBlock()(h string)  {
	message := b.prevHash
	message = message + b.nodeMAC + b.nodeIP + b.nodePe
	msgHash := sha256.Sum256([]byte(message))
	//进行十六进制字符串编码
	h = hex.EncodeToString(msgHash[:])
	return
}

//验证区块
func (b *bidBlock)Validate(){
	if b.hash != b.HashBlock(){
		err := errors.New("交易数据被修改")
		panic(err)
	}
}


